package com.kongge.viewdisplayframeworklib.model;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.kongge.viewdisplayframeworklib.control.PublicInterface;
import com.kongge.viewdisplayframeworklib.event.action.EQAction;
import com.kongge.viewdisplayframeworklib.event.action.EQGotoFrameAction;
import com.kongge.viewdisplayframeworklib.event.param.EQParam;
import com.kongge.viewdisplayframeworklib.model.queue.PageQueue;
import com.kongge.viewdisplayframeworklib.model.queue.PageQueueNode;
import com.kongge.viewdisplayframeworklib.util.EQConstans;

import java.util.LinkedList;
import java.util.List;

public class PageControlCreater {

	public AbsUIController createUIControl(int nPageId) {
		return createUIControl(new EQGotoFrameAction(EQAction.TYPE_ACTION, nPageId));
	}
	
	public AbsUIController createUIControl(EQAction gotoFrameAction) {
		int nPageId = ((EQGotoFrameAction) gotoFrameAction).getGotoFrameId();
		int focusUIControllerId = 0;
		AbsUIController control = null;
		PageNode pageNode = PublicInterface.getPageNodeById(nPageId);
		if (pageNode.getQueueId() != EQConstans.INVALID_ID) {
			focusUIControllerId = pageNode.getPageId();
			pageNode = PublicInterface.getPageNodeById(pageNode.getQueueId());
		}
		control = createUIControllByPageNode(pageNode, focusUIControllerId);
		if (control != null) {
			EQParam param = gotoFrameAction.getParam();
			if (param != null) {
				control.dispatchParam(param);
			}
		}
		return control;
	}

	private AbsUIController createUIControllByPageNode(PageNode pageNode, int focusUIControllerId) {
		AbsUIController control = null;
		if (pageNode != null) {
			int nLayoutId = PublicInterface.findLayoutResId(pageNode);
			ViewGroup viewGroup = inflaterLayout(nLayoutId);
			if (viewGroup != null) {
				if (pageNode instanceof PageQueueNode) {
					control = new PageQueue(pageNode, viewGroup);
					PageQueueNode pageQueueNode = (PageQueueNode) pageNode;
					((PageQueue) control).initUIControllers(createControllers(pageQueueNode.getSubPageNodeList(), focusUIControllerId), focusUIControllerId);
				} else {
					control = new Page(pageNode, viewGroup);
				}

			}
		}
		return control;
	}

	private ViewGroup inflaterLayout(int nLayoutId) {
		ViewGroup viewGroup = null;
		Activity mActivity = PublicInterface.getGloablActivity();
		if (mActivity != null) {
			LayoutInflater inflater = mActivity.getLayoutInflater();
			viewGroup = (ViewGroup) inflater.inflate(nLayoutId, null);
		}
		return viewGroup;
	}

	private List<AbsUIController> createControllers(List<PageNode> pageNodes, int focusUIControllerId) {
		if (pageNodes == null) {
			return null;
		}
		List<AbsUIController> absUIControllerList = new LinkedList<>();
		for (int i = 0; i < pageNodes.size(); i++) {
			absUIControllerList.add(createUIControllByPageNode(pageNodes.get(i), focusUIControllerId));
		}
		return absUIControllerList;
	}
}
